﻿using System;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data;
using DingTalkAgent.DBUtility;

namespace DingTalkAgent.SqlData
{
    //角色表
    public partial class Roles
    {
        #region	 T_Roles

        ///<summary>
        /// Exist
        ///</summary>
        public bool Exists(int ID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from T_Roles");
            strSql.Append(" where ");
            strSql.Append(" ID = @ID  ");
            SqlParameter[] parameters = {
                    new SqlParameter("@ID", SqlDbType.Int,4)
            };
            parameters[0].Value = ID;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }



        /// <summary>
        /// 增加一条T_Roles数据
        /// </summary>
        public int Add(DingTalkAgent.Model.Roles model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into T_Roles(");
            strSql.Append("RoleCode,Name,Navs,Active,Remark,User_ID");
            strSql.Append(") values (");
            strSql.Append("@RoleCode,@Name,@Navs,@Active,@Remark,@User_ID");
            strSql.Append(") ");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
                        new SqlParameter("@RoleCode", SqlDbType.VarChar,16) ,
                        new SqlParameter("@Name", SqlDbType.VarChar,64) ,
                        new SqlParameter("@Navs", SqlDbType.VarChar,1024) ,
                        new SqlParameter("@Active", SqlDbType.Int,4) ,
                        new SqlParameter("@Remark", SqlDbType.VarChar,1024) ,
                        new SqlParameter("@User_ID", SqlDbType.Int,4)

            };

            parameters[0].Value = model.RoleCode;
            parameters[1].Value = model.Name;
            parameters[2].Value = model.Navs;
            parameters[3].Value = model.Active;
            parameters[4].Value = model.Remark;
            parameters[5].Value = model.User_ID;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {

                return Convert.ToInt32(obj);

            }

        }


        /// <summary>
        /// 更新一条T_Roles数据
        /// </summary>
        public bool Update(DingTalkAgent.Model.Roles model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_Roles set ");

            strSql.Append(" RoleCode = @RoleCode , ");
            strSql.Append(" Name = @Name , ");
            strSql.Append(" Navs = @Navs , ");
            strSql.Append(" Active = @Active , ");
            strSql.Append(" Remark = @Remark , ");
            strSql.Append(" User_ID = @User_ID  ");
            strSql.Append(" where ID=@ID ");

            SqlParameter[] parameters = {
                        new SqlParameter("@ID", SqlDbType.Int,4) ,
                        new SqlParameter("@RoleCode", SqlDbType.VarChar,16) ,
                        new SqlParameter("@Name", SqlDbType.VarChar,64) ,
                        new SqlParameter("@Navs", SqlDbType.VarChar,1024) ,
                        new SqlParameter("@Active", SqlDbType.Int,4) ,
                        new SqlParameter("@Remark", SqlDbType.VarChar,1024) ,
                        new SqlParameter("@User_ID", SqlDbType.Int,4)

            };

            parameters[0].Value = model.ID;
            parameters[1].Value = model.RoleCode;
            parameters[2].Value = model.Name;
            parameters[3].Value = model.Navs;
            parameters[4].Value = model.Active;
            parameters[5].Value = model.Remark;
            parameters[6].Value = model.User_ID;
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 启用/禁用用户状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Active"></param>
        /// <returns></returns>
        public bool UpdateStatus(int Id, int Active)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_Roles set ");
            strSql.Append(" Active = @Active");
            strSql.Append(" where ID=@ID ");

            SqlParameter[] parameters = {
                        new SqlParameter("@ID", SqlDbType.Int,4) ,
                        new SqlParameter("@Active", SqlDbType.Int,4)
            };
            parameters[0].Value = Id;
            parameters[1].Value = Active;
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 删除一条T_Roles数据
        /// </summary>
        public bool Delete(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_Roles ");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
                    new SqlParameter("@ID", SqlDbType.Int,4)
            };
            parameters[0].Value = ID;


            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条T_Roles数据
        /// </summary>
        public bool Deletes(string ids)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_Roles ");
            strSql.Append(" where ID in (" + ids + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public DingTalkAgent.Model.Roles GetModel(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID, RoleCode, Name, Navs, Active, Remark, User_ID  ");
            strSql.Append("  from T_Roles ");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
                    new SqlParameter("@ID", SqlDbType.Int,4)
            };
            parameters[0].Value = ID;


            DingTalkAgent.Model.Roles model = new DingTalkAgent.Model.Roles();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["ID"].ToString() != "")
                {
                    model.ID = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
                }
                model.RoleCode = ds.Tables[0].Rows[0]["RoleCode"].ToString();
                model.Name = ds.Tables[0].Rows[0]["Name"].ToString();
                model.Navs = ds.Tables[0].Rows[0]["Navs"].ToString();
                if (ds.Tables[0].Rows[0]["Active"].ToString() != "")
                {
                    model.Active = int.Parse(ds.Tables[0].Rows[0]["Active"].ToString());
                }
                model.Remark = ds.Tables[0].Rows[0]["Remark"].ToString();
                if (ds.Tables[0].Rows[0]["User_ID"].ToString() != "")
                {
                    model.User_ID = int.Parse(ds.Tables[0].Rows[0]["User_ID"].ToString());
                }

                return model;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 获得数据T_Roles列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * ");
            strSql.Append(" FROM T_Roles ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得数据T_Roles列表
        /// </summary>
        public IEnumerable<DingTalkAgent.Model.Roles> IEnumGetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID, RoleCode, Name, Navs, Active, Remark, User_ID");
            strSql.Append(" FROM T_Roles ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            DataSet ds = DbHelperSQL.Query(strSql.ToString());
            DingTalkAgent.Model.Roles model;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                model = new DingTalkAgent.Model.Roles();
                if (dr["ID"].ToString() != "")
                {
                    model.ID = int.Parse(dr["ID"].ToString());
                }
                model.RoleCode = dr["RoleCode"].ToString();
                model.Name = dr["Name"].ToString();
                model.Navs = dr["Navs"].ToString();
                if (dr["Active"].ToString() != "")
                {
                    model.Active = int.Parse(dr["Active"].ToString());
                }
                model.Remark = dr["Remark"].ToString();
                if (dr["User_ID"].ToString() != "")
                {
                    model.User_ID = int.Parse(dr["User_ID"].ToString());
                }

                yield return model;
            }
        }
        /// <summary>
        /// 获得数据 T_Roles分页列表
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="total">总记录数</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        /// 

        public List<DingTalkAgent.Model.Roles> GetPageList(int PageIndex, int PageSize, out int total, string keyword)
        {
            int Skip = (PageIndex - 1) * PageSize;
            //count
            StringBuilder strSqlCount = new StringBuilder();
            strSqlCount.Append("Select @total=count(ID) From T_Roles ");
            //data
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select Top " + PageSize + " * from (");
            strSql.Append("select  row_number() OVER (ORDER BY ID Desc) AS row, ID, RoleCode, Name, Navs, Active, Remark, User_ID ");
            strSql.Append(" FROM  T_Roles ");
            //where
            StringBuilder Where = new StringBuilder();
            Where.Append(" where 1=1");
            if (keyword.Trim() != "")
            {
                Where.Append(" and (Name like @keyword or Active like @keyword or Remark like @keyword) ");
            }
            strSqlCount.Append(Where.ToString());
            strSql.Insert(0, strSqlCount.ToString() + ";");
            strSql.Append(Where.ToString());
            strSql.Append(") as a ");
            strSql.Append(" Where a.row>" + Skip);

            //parameters
            SqlParameter[] parameters = {
                    new SqlParameter("@total", SqlDbType.Int,4),
                    new SqlParameter("@keyword", SqlDbType.VarChar,64)
                    };
            parameters[0].Direction = ParameterDirection.Output;
            parameters[1].Value = "%" + keyword.Trim() + "%";

            List<DingTalkAgent.Model.Roles> list = new List<DingTalkAgent.Model.Roles>();
            DingTalkAgent.Model.Roles model = new DingTalkAgent.Model.Roles();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            total = Convert.ToInt32(parameters[0].Value);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                model = new DingTalkAgent.Model.Roles();
                if (dr["ID"].ToString() != "")
                {
                    model.ID = int.Parse(dr["ID"].ToString());
                }
                model.RoleCode = dr["RoleCode"].ToString();
                model.Name = dr["Name"].ToString();
                model.Navs = dr["Navs"].ToString();
                if (dr["Active"].ToString() != "")
                {
                    model.Active = int.Parse(dr["Active"].ToString());
                }
                model.Remark = dr["Remark"].ToString();
                if (dr["User_ID"].ToString() != "")
                {
                    model.User_ID = int.Parse(dr["User_ID"].ToString());
                }

                list.Add(model);
            }
            return list;
        }
        #endregion


        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="RoleID">RoleID</param>
        /// <param name="ints">权限级合</param>
        /// <returns></returns>
        public int SaveCheckboxPower(int RoleID, List<int> ints)
        {
            List<string> List = new List<string>();
            //删除
            List.Add("delete T_Roles_Action where Role_ID=" + RoleID + " ");
            foreach (var i in ints)
            {
                List.Add("insert into T_Roles_Action values(" + RoleID + "," + i + ") ");
            }
            return DbHelperSQL.ExecuteSqlTran(List);
        }

        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="RoleID">RoleID</param>
        /// <param name="ints">权限级合</param>
        /// <returns></returns>
        public int SaveRadioPower(int RoleID,System.Collections.Generic.Dictionary<int,int> DataPower)
        {
            List<string> List = new List<string>();
            List.Add("delete T_Roles_DataPower where Role_ID=" + RoleID + " ");
            foreach (KeyValuePair<int,int>i in DataPower)
            {
                List.Add("insert into T_Roles_DataPower values(" + RoleID + "," + i.Key + ","+i.Value+") ");
            }
            return DbHelperSQL.ExecuteSqlTran(List);
        }

        /// <summary>
        /// 根据Role获得Nav
        /// </summary>
        /// <param name="Level"></param>
        /// <returns></returns>
        public IEnumerable<DingTalkAgent.Model.SysNav> IEnumBuildNav(int Level)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append(@" SELECT [Nav_ID]
                                  ,[Parent_ID]
                                  ,[Name]
                                  ,[Alt]
                                  ,Ioc
	                              ,[Controller]
	                              ,[Action]
                              FROM [T_SysNav] Nav
                              left join (
		                            SELECT a.[Page_ID]
		                              ,a.[Name] pageName
		                              ,a.[Controller]
		                              ,a.[Action]
		                              ,b.Act_ID
		                            FROM [T_SysPage] a
		                              left join T_SysAction b on a.Page_ID=b.Page_ID
		                            where a.Controller=b.Controller and a.Action=b.Action 
			  
	                              ) as Page on Nav.Page_ID=Page.Page_ID
                              where active=1 and (Act_ID in(select Act_ID from T_Roles_Action where Role_ID=@level_ID) or Parent_ID=-1)
                              order by OrderID Desc
                            ");
            //parameters
            SqlParameter[] parameters = {
                    new SqlParameter("@level_ID", SqlDbType.Int,4)
                    };
            parameters[0].Value = Level;
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            DingTalkAgent.Model.SysNav model;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                model = new DingTalkAgent.Model.SysNav();
                if (dr["Nav_ID"].ToString() != "")
                {
                    model.Nav_ID = int.Parse(dr["Nav_ID"].ToString());
                }
                if (dr["Parent_ID"].ToString() != "")
                {
                    model.Parent_ID = int.Parse(dr["Parent_ID"].ToString());
                }
                model.Name = dr["Name"].ToString();
                model.Url = "/" + dr["Controller"].ToString() + "/" + dr["Action"].ToString();
                model.Ioc = dr["Ioc"].ToString();
                model.Alt = dr["Alt"].ToString();


                yield return model;
            }
        }


        /// <summary>
        /// 获取角色功能对应表
        /// </summary>
        /// <returns></returns>
        public List<Model.role_action> queryRoleList()
        {

            var dic = new Dictionary<string, object>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select a.ID as RoleID,a.Name,c.* from T_Roles as a
left join T_Roles_Action as b on a.ID=b.Role_ID
left join T_SysAction as c on b.Act_ID=c.Act_ID");
            SqlParameter[] parameters = {
                    new SqlParameter("@Role_ID", SqlDbType.Int,4),
                    new SqlParameter("@Controller", SqlDbType.VarChar,64),
                    new SqlParameter("@Action", SqlDbType.VarChar,64)

                    };
            parameters[0].Value = 0;
            parameters[1].Value = "";
            parameters[2].Value = "";
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            List<Model.role_action> list = new List<Model.role_action>();
            Model.role_action model = null;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                model = new Model.role_action();
                if (dr["RoleID"].ToString() != "")
                {
                    model.RoleID = int.Parse(dr["RoleID"].ToString());
                }
                if (dr["Act_ID"].ToString() != "")
                {
                    model.Act_ID = int.Parse(dr["Act_ID"].ToString());
                }
                if (dr["Page_ID"].ToString() != "")
                {
                    model.Page_ID = int.Parse(dr["Page_ID"].ToString());
                }
                model.Name = dr["Name"].ToString();
                model.Act_Name = dr["Act_Name"].ToString();
                model.Action = dr["Action"].ToString();
                model.Controller = dr["Controller"].ToString();
                list.Add(model);
            }
            return list;
        }


        #region 以前
        /// <summary>
        /// 判断是否有访问权限
        /// </summary>
        /// <param name="Role_ID"></param>
        /// <param name="controller"></param>
        /// <param name="Action"></param>
        /// <returns></returns>
        public bool isVisit(int Role_ID, string controller, string Action)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"select count(a.Role_ID) from dbo.T_Roles_Action a
                            left join dbo.T_SysAction b on a.Act_ID=b.Act_ID
                            where a.Role_ID=@Role_ID
                                  and b.Controller=@Controller
                                  and b.Action=@Action ");
            SqlParameter[] parameters = {
                    new SqlParameter("@Role_ID", SqlDbType.Int,4),
                    new SqlParameter("@Controller", SqlDbType.VarChar,64),
                    new SqlParameter("@Action", SqlDbType.VarChar,64)
                    };
            parameters[0].Value = Role_ID;
            parameters[1].Value = controller;
            parameters[2].Value = Action;
            var result = Convert.ToInt32(DbHelperSQL.GetSingle(strSql.ToString(), parameters));
            if (result > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 在进行导航页请求时，获取可操作的Action
        /// </summary>
        /// <param name="Role_ID">用户编号</param>
        /// <param name="controller"></param>
        /// <param name="Action"></param>
        /// <returns></returns>
        public List<string> getPageAction(int Role_ID, string controller, string Action)
        {

            var dic = new Dictionary<string, object>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT [Action]
                            FROM [T_SysAction]
                            where Page_ID in (select Page_ID From  T_SysPage where Controller=@Controller and Action=@Action)
                            and Act_ID in (select Act_ID from T_Roles_Action where Role_ID=@Role_ID)");
            SqlParameter[] parameters = {
                    new SqlParameter("@Role_ID", SqlDbType.Int,4),
                    new SqlParameter("@Controller", SqlDbType.VarChar,64),
                    new SqlParameter("@Action", SqlDbType.VarChar,64)

                    };
            parameters[0].Value = Role_ID;
            parameters[1].Value = controller;
            parameters[2].Value = Action;
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            List<string> list = new List<string>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //dic.Add(dr[0].ToString(), dr[0].ToString());
                list.Add(dr[0].ToString());
            }
            return list;
        }

        #endregion
    }
}
